package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 缓存商户类型
     * @return
     */
    public Result queryList() {
        //先从Redis中查,这里的常量值是固定前缀+店铺id
        List<String> shopTypes = stringRedisTemplate.opsForList().range("cache:shopType:", 0, -1);
        //如果不为空(查询到了则1转为ShopType对象并返回)
        if(!shopTypes.isEmpty()){
            List<ShopType> shopTypes1 = shopTypes.stream().map(type -> JSONUtil.toBean(type, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(shopTypes1);
        }
        //如果为空(没查询到则从数据库查询并存入Redis)
        List<ShopType>tmp = query().orderByAsc("sort").list();
        if(tmp==null){
            return Result.fail("商户类型不存在!");
        }
        //查到了转为json字符串,存入redis
        shopTypes = tmp.stream().map(type -> JSONUtil.toJsonStr(type)).collect(Collectors.toList());
        stringRedisTemplate.opsForList().leftPushAll("cache:shopType:", shopTypes);
        return Result.ok(tmp);
    }

}
